package com.itheima.reggie.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public void delete() {
        LambdaQueryWrapper<Cart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(lqw);

    }

    @Override
    public Cart update(Cart cartParam) {

        LambdaQueryWrapper<Cart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Cart::getUserId, UserHolder.get().getId());
        lqw.eq(Objects.nonNull(cartParam.getDishId()), Cart::getDishId, cartParam.getDishId());
        lqw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());
        Cart cart = cartMapper.selectOne(lqw);

        if (cart.getNumber() == 1) {
            cartMapper.deleteById(cart);
            cart.setNumber(0);
            return cart;
        }else {
            cartParam.setNumber(cartParam.getNumber() - 1);
            cartMapper.updateById(cartParam);
            return cartParam;
        }
    }

    @Override
    public List<Cart> findAll() {
        LambdaQueryWrapper<Cart> l = new LambdaQueryWrapper<>();
        l.eq(Cart::getUserId, UserHolder.get().getId());
        List<Cart> carts = cartMapper.selectList(l);
        return carts;
    }

    @Override
    public Cart save(Cart cart) {
        //先判断当前的cartparam是否已经在购物车了
        //创建查询条件对象
        LambdaQueryWrapper<Cart> lqw = new LambdaQueryWrapper();
        //设置查询条件同一时间点只能添加菜品或者套餐的其中的一个
        lqw.eq(Cart::getUserId, UserHolder.get().getId());//指定用户的
        lqw.eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId());
        lqw.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        //执行查询
        Cart cart1 = cartMapper.selectOne(lqw);
        if (cart1 != null) {
 //已经添加过了修改数量
            cart1.setNumber(cart1.getNumber() + 1);
            //更新返回cart1
            cartMapper.updateById(cart1);
            return cart1;
        } else {
            cart.setUserId(UserHolder.get().getId());
            //补全数量
            cart.setNumber(1);
            //补全创建时间
            cart.setCreateTime(new Date());
            //保存
            cartMapper.insert(cart);
            return cart;
        }
    }
}
